package net.bcxuexi.socket.stream.inhandle;


import net.bcxuexi.config.Config;
import net.bcxuexi.pool.Dispatcher;
import net.bcxuexi.pool.FIFODispatcher;
import net.bcxuexi.socket.SocketManager;
import net.bcxuexi.socket.model.SocketModel;
import net.bcxuexi.socket.stream.StreamData;
import net.bcxuexi.tools.MyLog;


/**
 * 输入数据流处理服务。采用线程池处理,最多20个线程。
 * 输入数据流包括：
 * 1 外网服务器发送的数据流
 */
public class DataInputStreamHandlerServer {
	private static DataInputStreamHandlerServer dataServer;
	// 待办任务监听调度器
	private Dispatcher dispatcher;
	
	private DataInputStreamHandlerServer(){
		dispatcher = new FIFODispatcher(1,1);
	}
	public void addInputStream(StreamData inputStreamData){
		try {
			DataInputHandler handler = new DataInputHandler(inputStreamData);
			dispatcher.addTask(handler);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	public static synchronized DataInputStreamHandlerServer getInstance(){
		if(dataServer==null){
			dataServer = new DataInputStreamHandlerServer();
			dataServer.dispatcher.startDispatch();
		}
		return dataServer;
	}
	/**
	 * 数据流处理类
	 * @author graphics
	 *
	 */
	public static class DataInputHandler implements Runnable{
		private StreamData inputStreamData;
		public DataInputHandler(StreamData inputStreamData){
			this.inputStreamData = inputStreamData;
		}
		@Override
		public void run() {
			if(Config.debug){
				String dmsg = new String(inputStreamData.data,0,inputStreamData.total);
				MyLog.info("接收到服务器data数据："+dmsg);
			}
			
			/*
			 * 解析协议
			 * 第0个字节为2:代表数据通信
			 * 第1到8个字节:代表proxy socket的connId
			 * 第9到20个字节:代表内网服务器的4位ip 192168001155
			 * 第21到25个字节:代表内网服务器的端口 如:61235,08080
			 */
			byte[] msg = inputStreamData.data;
			String proxySocketConnId = new String(msg,1,8);
			String innerIp = Integer.valueOf(new String(msg,9,3))+"."+Integer.valueOf(new String(msg,12,3))+"."+Integer.valueOf(new String(msg,15,3))+"."+Integer.valueOf(new String(msg,18,3));
			int innerPort = Integer.valueOf(new String(msg,21,5));
			//找到内网指定服务连接socket(如果是http协议以后要单独处理),没有则新建
			SocketModel innerSocketModel = SocketManager.getInstance().createInnerSocket(proxySocketConnId, innerIp, innerPort);
			//数据发送到内网指定服务器
			if(innerSocketModel!=null){
				byte[] data = new byte[msg.length-26];
				for(int i=0;i<data.length;i++){
					data[i] = msg[26+i];
				}
				if(Config.debug){
					String dmsg = new String(data,0,data.length);
					MyLog.info("data数据去掉头部消息后："+dmsg);
				}
				StreamData innerStreamData = new StreamData();
				innerStreamData.setData(data);
				innerStreamData.setSocketModel(innerSocketModel);
				innerStreamData.setTotal(data.length);
				try {
					innerSocketModel.getWriteStream().addData(innerStreamData);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
		}
		
	}
}
